/*************************************************************************
	> File Name: week16-1-message.c
	> Author: Potter
	> Mail: tobewhatwewant@gmail.com 
	> Created Time: 2014年06月18日 星期三 14时13分35秒
 ************************************************************************/

/*
* int msgget(key_t key, int msgflg)
*
* int msgsnd(int msqid, struct msgbuf * msgp, int msgsz, int msgflg)
*
* int msgrcv(int msqid, struct msgbuf * msgp, int msgsz, long msgtype, int msgflg)
*
* int msgctl(int msqid, int cmd, struct msqid_ds *buf)
* */

#include<stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/wait.h>


struct msgbuf {
    long mtype;
    char mtext[1024];
};

int main(int argc, char * argv[]) {
    int msqid;
	int pid;
    // char child_say[100]; //= "Hi, this is child process sending message!";
    struct msgbuf child;
    struct msgbuf parent;

    while((msqid = msgget(IPC_PRIVATE, IPC_CREAT | 0600)) == -1) {
        perror("Msgget");
    }

    while((pid = fork()) == -1) {
        perror("Fork");
    }

    if(pid == 0) {
        fprintf(stdout, "This is child process(pid=%d)\n", getpid());
        // @TODO
        child.mtype = 1;
        strcpy(child.mtext, "Hi, this is child process sending message!");
        while(msgsnd(msqid, &child, strlen(child.mtext), 0) == -1) {
            perror("msgsnd");
        }
    } else {
        wait(0);
        fprintf(stdout, "This is parent process (pid=%d)\n", getpid());
        while ( msgrcv(msqid, &parent, 1024, 1, 0) == -1) {
            perror("Msgrcv");
        }
        fprintf(stdout, "%s\n", parent.mtext);
        while(msgctl(msqid, IPC_RMID, NULL) == -1) {
            perror("Msgctl");
        }
    }

	return 0;
}
